package com.rupeng.web.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.github.pagehelper.PageInfo;
import com.rupeng.pojo.User;
import com.rupeng.service.UserService;
import com.rupeng.util.AjaxResult;
import com.rupeng.util.CommonUtils;

@Controller
@RequestMapping("/user")
public class UserController {
	@Autowired
	private UserService userService;
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
	}
	@RequestMapping("/list.do")
	public ModelAndView list(Integer curr, Date beginTime, Date endTime, String param) {
		if (curr==null) {
			curr = 1;
		}
		if (endTime!=null) {
			endTime.setTime(endTime.getTime()+1000*60*60*24-1);
		}
		if (!CommonUtils.isEmpty(param)) {
			param="%"+param+"%";
		} else {
			param = null;
		}
		Map<String, Object> params = new HashMap<String,Object>();
		params.put("beginTime", beginTime);
		params.put("endTime", endTime);
		params.put("param", param);
		PageInfo<User> pageInfo = userService.search(curr,10,params);
		return new ModelAndView("user/list","pageInfo",pageInfo);
	}
	@RequestMapping("/toTeacher.do")
	public @ResponseBody AjaxResult toTeacher(Long id) {
		User user = userService.selectOne(id);
		user.setIsTeacher(!user.getIsTeacher());
		userService.update(user);
		if (user.getIsTeacher()) {
			return AjaxResult.successInstance("已将其身份设置为老师");
		} else {
			return AjaxResult.successInstance("已撤回老师身份");
		}
	}
	@RequestMapping(value="/update.do",method=RequestMethod.GET)
	public ModelAndView updatePage(Long id) {
		User user = userService.selectOne(id);
		return new ModelAndView("user/update", "user", user);
	}
	@RequestMapping(value="/update.do",method=RequestMethod.POST)
	public @ResponseBody AjaxResult updateSubmit(Long id, String name, Boolean isMale, String email, String phone, String school) {
		if (id==null || isMale==null || CommonUtils.isEmpty(name) || CommonUtils.isEmpty(email) || CommonUtils.isEmpty(phone) || CommonUtils.isEmpty(school)) {
			return AjaxResult.errorInstance("表单数据不完整");
		}
		User user = userService.selectOne(id);
		user.setName(name);
		user.setIsMale(isMale);
		user.setEmail(email);
		user.setPhone(phone);
		user.setSchool(school);
		userService.update(user);
		return AjaxResult.successInstance("修改用户信息成功");
	}
}
